package co.recloud.ariadne.request;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import co.recloud.ariadne.model.Host;

public class Connection {
	private Socket clientSocket;
	private ObjectInputStream inputStream;
	private ObjectOutputStream outputStream;
	private Host target;
	private Long id;
	/**
	 * @return the clientSocket
	 */
	public Socket getClientSocket() {
		return clientSocket;
	}
	/**
	 * @param clientSocket the clientSocket to set
	 * @throws IOException 
	 */
	public void setClientSocket(Socket clientSocket) throws IOException {
		this.clientSocket = clientSocket;
		inputStream = null;
		outputStream = null;
	}
	/**
	 * @return the inputStream
	 */
	public ObjectInputStream getInputStream() {
		return inputStream;
	}
	/**
	 * @return the outputStream
	 */
	public ObjectOutputStream getOutputStream() {
		return outputStream;
	}
	/**
	 * @return the target
	 */
	public Host getTarget() {
		return target;
	}
	/**
	 * @param target the target to set
	 */
	public void setTarget(Host target) {
		this.target = target;
	}
	/**
	 * @param id the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}
	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}
	
	public void write(Request request) {
		if(outputStream == null) {
			try {
				outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(outputStream != null) {
			try {
				outputStream.writeObject(request);
				outputStream.flush();
				outputStream.reset();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public Object read() {
		Object result = null;
		if(inputStream == null) {
			try {
				inputStream = new ObjectInputStream(clientSocket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(inputStream != null) {
			try {
				result = inputStream.readObject();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
}
